﻿@using Gurux.DLMS.AMI.Components.Enums
@using System.Diagnostics.CodeAnalysis
@using System.Globalization

@inherits InputBase<int>

<input type="time" class="@CssClass" step="@Step"
       @attributes="AdditionalAttributes" value="@BindConverter.FormatValue(CurrentValueAsString)" onchange="@((ChangeEventArgs __e) => CurrentValueAsString = Convert.ToString(__e.Value))" />
@code {
    /// <summary>
    /// Value is get as a milliseconds.
    /// </summary>
    [Parameter]
    public TimeSpanUnit TimeSpanUnit { get; set; } = TimeSpanUnit.Second;

    private int Step
    {
        get
        {
            int value = 60;
            switch (TimeSpanUnit)
            {
                case TimeSpanUnit.Second:
                    value = 1;
                    break;
                case TimeSpanUnit.Minute:
                    value = 60;
                    break;
                case TimeSpanUnit.Hour:
                    value = 3600;
                    break;
                default:
                    break;
            }
            return value;
        }
    }


    protected override bool TryParseValueFromString(string? value,
    [MaybeNullWhen(false)] out int result,
    [NotNullWhen(false)] out string validationErrorMessage)
    {
        validationErrorMessage = "";
        try
        {
            if (value != null)
            {
                switch (TimeSpanUnit)
                {
                    case TimeSpanUnit.Second:
                        result = (int)TimeSpan.Parse(value).TotalSeconds;
                        break;
                    case TimeSpanUnit.Minute:
                        result = (int)TimeSpan.Parse(value).TotalMinutes;
                        break;
                    case TimeSpanUnit.Hour:
                        result = (int)TimeSpan.Parse(value).TotalHours;
                        break;
                    default:
                        result = 0;
                        break;
                }
            }
            else
            {
                result = 0;
            }
        }
        catch (Exception ex)
        {
            result = 0;
            validationErrorMessage = ex.Message;
            return false;
        }
        return true;
    }

    protected override string? FormatValueAsString(int value)
    {
        string result;
        switch (TimeSpanUnit)
        {
            case TimeSpanUnit.Second:
                result = TimeSpan.FromSeconds(value).ToString();
                break;
            case TimeSpanUnit.Minute:
                result = TimeSpan.FromMinutes(value).ToString("hh\\:mm");
                break;
            case TimeSpanUnit.Hour:
                result = TimeSpan.FromHours(value).ToString();
                break;
            default:
                result = "";
                break;
        }
        return result;
    }
}